#!/usr/bin/env python2
# -*- coding: utf-8 -*-

import sys
import errno

from gbase_utils import parser, _derror, _exec_cmd


class GbaseNode(object):
    def __init__(self, num):
        self.num = num
        self.parser_conf()

    def parser_conf(self):
        conf = parser()
        cluster = conf['cluster']

        num = cluster['num']
        if self.num not in range(num):
            _derror('Confed nodes num [0..%d), your input %d' % (
                num, self.num))
            exit(errno.EINVAL)

        self.passwd = cluster['password']
        self.conf = conf['nodes'][self.num]
        for hostname, net in self.conf.iteritems():
            self.hostname = hostname
            self.nets = net

    def set_hostname(self):
        hostname = self.hostname
        print "set Hostname : " + hostname
        cmd = 'hostname %s && echo "%s" > /etc/hostname' % (hostname, hostname)
        _exec_cmd(cmd, 'set hostname %s failed' % hostname, True)

    def set_passwd(self):
        passwd = self.passwd
        print "Password for root : " + passwd
        cmd = 'echo "%s"| passwd --stdin root' % (passwd)
        _exec_cmd(cmd, "set passwd (%s) failed" % passwd, True)

    def set_one(self, eth, ip):
        ip = ip.split('/')[0]
        path = '/etc/sysconfig/network-scripts/ifcfg-' + eth
        cmd = 'sed -ri s"%%^\s*ONBOOT=no%%ONBOOT=yes%%g" %s' % (path)
        _exec_cmd(cmd, "set ip onboot failed")
        cmd = 'sed -ri s"%%^\s*IPADDR=([0-9]{1,3}.){3}\S*$%%IPADDR=%s%%g" %s' % (
                ip, path)
        _exec_cmd(cmd, "set %s:%s failed" % (eth, ip), True)

    def set_ip(self):
        nets = self.nets
        for eth, ip in nets.iteritems():
            self.set_one(eth, ip)

        # cmd = '/etc/init.d/network restart'
        cmd = 'systemctl restart network'
        print 'restart network...'
        _exec_cmd(cmd, "restart network failed")

    def run(self):
        print '''
            1.设置hostname
            2.设置passwd
            3.设置ip
        '''
        print 'step 1 : 设置hostname...'
        self.set_hostname()
        print 'step 1 successed'

        print 'step 2 : 设置passwd...'
        self.set_passwd()
        print 'step 2 successed'

        print 'step 3 : 设置ip...'
        self.set_ip()
        print 'step 3 successed'

if __name__ == "__main__":
    args = sys.argv
    if len(args) < 2 or not args[1].isdigit():
        _derror('usage:')
        _derror('\t' + args[0] + ' <num of node [0..num) >')
        exit(errno.EINVAL)

    num = int(args[1])
    gbn = GbaseNode(num)
    gbn.run()
    print('\nSuccessed!')
